/**
 * API服务类 - 与后端API进行交互
 */
class ApiService {
	constructor() {
		this.baseURL = 'http://localhost:8080';
		this.token = null;
		this.init();
	}

	init() {
		// 从本地存储获取token
		this.token = uni.getStorageSync('token');
	}

	/**
	 * 设置认证token
	 */
	setToken(token) {
		this.token = token;
		uni.setStorageSync('token', token);
	}

	/**
	 * 清除认证token
	 */
	clearToken() {
		this.token = null;
		uni.removeStorageSync('token');
	}

	/**
	 * 通用请求方法
	 */
	async request(url, options = {}) {
		const {
			method = 'GET',
			data = {},
			headers = {},
			requireAuth = true
		} = options;

		// 构建请求头
		const requestHeaders = {
			'Content-Type': 'application/json',
			...headers
		};

		// 添加认证头
		if (requireAuth && this.token) {
			requestHeaders['Authorization'] = `Bearer ${this.token}`;
		}

		try {
			const response = await new Promise((resolve, reject) => {
				uni.request({
					url: `${this.baseURL}${url}`,
					method,
					data,
					header: requestHeaders,
					success: resolve,
					fail: reject
				});
			});

			// 检查响应状态
			if (response.statusCode >= 200 && response.statusCode < 300) {
				return response.data;
			} else {
				throw new Error(`HTTP ${response.statusCode}: ${response.data?.message || '请求失败'}`);
			}
		} catch (error) {
			console.error('API请求失败:', error);
			throw error;
		}
	}

	// ==================== 用户认证相关 ====================

	/**
	 * 用户登录
	 */
	async login(credentials) {
		return await this.request('/api/v1/auth/login', {
			method: 'POST',
			data: credentials,
			requireAuth: false
		});
	}

	/**
	 * 用户注册
	 */
	async register(userInfo) {
		return await this.request('/api/v1/auth/register', {
			method: 'POST',
			data: userInfo,
			requireAuth: false
		});
	}

	/**
	 * 发送验证码
	 */
	async sendVerificationCode(data) {
		return await this.request('/api/v1/auth/send-code', {
			method: 'POST',
			data: data,
			requireAuth: false
		});
	}

	/**
	 * 获取用户信息
	 */
	async getUserProfile() {
		return await this.request('/api/v1/user/profile');
	}

	/**
	 * 更新用户信息
	 */
	async updateUserProfile(profileData) {
		return await this.request('/api/v1/user/profile', {
			method: 'PUT',
			data: profileData
		});
	}

	/**
	 * 刷新访问令牌
	 */
	async refreshToken(refreshToken) {
		return await this.request('/api/v1/auth/refresh', {
			method: 'POST',
			data: { refreshToken },
			requireAuth: false
		});
	}

	/**
	 * 用户登出
	 */
	async logout() {
		return await this.request('/api/v1/auth/logout', {
			method: 'POST',
			data: {}
		});
	}

	// ==================== 占卜相关 ====================

	/**
	 * 时间起卦
	 */
	async timeDivination(data) {
		return await this.request('/api/v1/divination/time', {
			method: 'POST',
			data: {
				question: data.question,
				useCurrentTime: data.useCurrentTime !== undefined ? data.useCurrentTime : true,
				divinationTime: data.divinationTime,
				algorithm: data.algorithm || 'TRADITIONAL',
				...data
			}
		});
	}

	/**
	 * 数字起卦
	 */
	async numberDivination(data) {
		return await this.request('/api/v1/divination/number', {
			method: 'POST',
			data: {
				question: data.question,
				numbers: [data.upperNumber, data.lowerNumber],
				algorithm: data.algorithm || 'TRADITIONAL',
				...data
			}
		});
	}

	/**
	 * 文本起卦
	 */
	async textDivination(data) {
		return await this.request('/api/v1/divination/text', {
			method: 'POST',
			data: {
				question: data.question,
				inputText: data.text,
				sourceType: data.sourceType || 'TEXT',
				algorithm: data.algorithm || 'TEXT_HASH',
				nlpAnalysis: data.nlpAnalysis || false,
				...data
			}
		});
	}

	/**
	 * 图片起卦
	 */
	async imageDivination(data) {
		return await this.request('/api/v1/divination/image', {
			method: 'POST',
			data: {
				question: data.question,
				algorithm: data.algorithm || 'IMAGE_HASH',
				extractFeatures: data.extractFeatures || false,
				...data
			}
		});
	}

	/**
	 * AI智能解读
	 */
	async aiInterpret(data) {
		return await this.request('/api/v1/ai/interpret', {
			method: 'POST',
			data: {
				hexagramCode: data.hexagramCode,
				question: data.question,
				context: data.context,
				aiModel: data.aiModel,
				interpretationLevel: data.interpretationLevel,
				...data
			}
		});
	}

	// ==================== 占卜记录相关 ====================

	/**
	 * 获取占卜记录列表
	 */
	async getDivinationRecords(params = {}) {
		const queryString = Object.keys(params)
			.map(key => `${key}=${encodeURIComponent(params[key])}`)
			.join('&');
		
		const url = queryString ? `/api/v1/user/divination-records?${queryString}` : '/api/v1/user/divination-records';
		return await this.request(url);
	}

	/**
	 * 获取单个占卜记录详情
	 */
	async getDivinationRecord(recordId) {
		return await this.request(`/api/v1/user/divination-records/${recordId}`);
	}

	/**
	 * 保存占卜记录
	 */
	async saveDivinationRecord(recordData) {
		return await this.request('/api/v1/user/divination-records', {
			method: 'POST',
			data: recordData
		});
	}

	/**
	 * 删除占卜记录
	 */
	async deleteDivinationRecord(recordId) {
		return await this.request(`/api/v1/user/divination-records/${recordId}`, {
			method: 'DELETE'
		});
	}

	/**
	 * 更新记录标签
	 */
	async updateRecordTags(recordId, tags) {
		return await this.request(`/api/v1/user/divination-records/${recordId}/tags`, {
			method: 'PUT',
			data: tags
		});
	}

	// ==================== 收藏相关 ====================

	/**
	 * 获取收藏列表
	 */
	async getFavoriteList(params = {}) {
		const queryString = Object.keys(params)
			.map(key => `${key}=${encodeURIComponent(params[key])}`)
			.join('&');
		
		const url = queryString ? `/api/v1/user/favorites?${queryString}` : '/api/v1/user/favorites';
		return await this.request(url);
	}

	/**
	 * 添加/取消收藏
	 */
	async toggleFavorite(favoriteData) {
		return await this.request('/api/v1/user/favorites', {
			method: 'POST',
			data: favoriteData
		});
	}

	// ==================== 用户设置相关 ====================

	/**
	 * 获取用户占卜设置
	 */
	async getUserDivinationSettings() {
		return await this.request('/api/v1/user/settings');
	}

	/**
	 * 更新用户占卜设置
	 */
	async updateUserDivinationSettings(settings) {
		return await this.request('/api/v1/user/settings', {
			method: 'PUT',
			data: settings
		});
	}

	/**
	 * 更新心情状态
	 */
	async updateMoodStatus(userId, moodStatus) {
		return await this.request(`/api/v1/user/${userId}/mood`, {
			method: 'PUT',
			data: {
				moodStatus: moodStatus
			}
		});
	}

	// ==================== 占卜反馈相关 ====================

	/**
	 * 提交占卜反馈
	 */
	async submitDivinationFeedback(feedback) {
		return await this.request('/api/v1/divination/feedback', {
			method: 'POST',
			data: feedback
		});
	}

	/**
	 * 获取用户反馈记录
	 */
	async getUserFeedback(userId) {
		return await this.request(`/api/v1/divination/feedback/user/${userId}`);
	}

	/**
	 * 分析反馈数据
	 */
	async analyzeFeedback() {
		return await this.request('/api/v1/divination/feedback/analyze', {
			method: 'POST'
		});
	}

	// ==================== 统计数据相关 ====================

	/**
	 * 获取心情统计
	 */
	async getMoodStats() {
		return await this.request('/api/v1/divination/feedback/stats/mood');
	}

	/**
	 * 获取卦象统计
	 */
	async getHexagramStats() {
		return await this.request('/api/v1/divination/feedback/stats/hexagram');
	}

	/**
	 * 获取城市统计
	 */
	async getCityStats() {
		return await this.request('/api/v1/divination/feedback/stats/city');
	}

	// ==================== 六十四卦信息 ====================

	/**
	 * 获取六十四卦基础信息
	 */
	async getAllHexagrams() {
		return await this.request('/api/v1/hexagrams');
	}

	/**
	 * 获取单个卦象详细信息
	 */
	async getHexagramDetail(hexagramId) {
		return await this.request(`/api/v1/hexagrams/${hexagramId}`);
	}

	// ==================== 工具方法 ====================

	/**
	 * 处理API错误
	 */
	handleError(error) {
		console.error('API错误:', error);
		
		// 根据错误类型显示不同的提示
		if (error.message.includes('401')) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			// 跳转到登录页面
			uni.navigateTo({
				url: '/pages/login/new-login'
			});
		} else if (error.message.includes('403')) {
			uni.showToast({
				title: '权限不足',
				icon: 'none'
			});
		} else if (error.message.includes('404')) {
			uni.showToast({
				title: '资源不存在',
				icon: 'none'
			});
		} else if (error.message.includes('500')) {
			uni.showToast({
				title: '服务器错误',
				icon: 'none'
			});
		} else {
			uni.showToast({
				title: error.message || '网络错误',
				icon: 'none'
			});
		}
	}

	/**
	 * 检查网络状态
	 */
	async checkNetworkStatus() {
		return new Promise((resolve) => {
			uni.getNetworkType({
				success: (res) => {
					resolve(res.networkType !== 'none');
				},
				fail: () => {
					resolve(false);
				}
			});
		});
	}
}

// 创建单例实例
const apiService = new ApiService();

export { ApiService };
export default apiService;